﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using EnvDTE;
using Microsoft.VisualStudio.CommandBars;
using VS4CRM.AddIn;
using VS4CRM.Lib;
using VS4CRM.Lib.CrmSDKMetadata;

namespace VS4CRM.AddIn.Commands
{
	public class EditCommand : CommandBase
	{        
		#region constants
		#endregion

		#region fields
		ProjectItem _entityItem = null;
		#endregion

		#region public properties
		#endregion

		#region constructor & descructor

		public EditCommand(DTEHandler dteHandler, ScriptUploader uploader)
			: base(dteHandler, uploader)
		{
		}

		public EditCommand(DTEHandler dteHandler, ScriptUploader uploader, Connect host)
			: base(dteHandler, uploader, host)
		{
		}

		#endregion

		#region public methods


		public static EditCommand Create(DTEHandler dteHandler, bool beginGroup, CommandBar[] commandbars, ScriptUploader uploader, Connect host)
		{
			EditCommand instance = new EditCommand(dteHandler, uploader, host);
			instance.CommandInstance = dteHandler.Menu.CreateCommand(
				"EDITENTITY",
				"Edit Entity",
				"Edit Enityt in CRM",
				"",
				new ExecuteDelegate(instance.Execute),
				new StatusDelegate(instance.Status));

			dteHandler.Menu.AddToCommandBars(instance.CommandInstance, beginGroup, commandbars);

			return instance;
		}

		internal override void Execute()
		{
            
			SelectedItem item = this.DTEInstance.AddInInstance.DTE.SelectedItems.Item(1);
			string extension = item.ProjectItem.Properties.Item("Extension").Value.ToString();
			if (extension == ".xml" && item.ProjectItem.ProjectItems.Count == 2)
			{
				_entityItem = item.ProjectItem;
				XmlDocument doc = new XmlDocument();
				doc.Load(_entityItem.get_FileNames(1));

				XmlNode entityNode = doc.SelectSingleNode("/ImportExportXml/Entities/Entity/Name");
				if (entityNode != null)
				{
					bool checkOutResult = true;
					SourceControl sourceControl = DTEInstance.Application.SourceControl;
					if (sourceControl.IsItemUnderSCC(item.ProjectItem.get_FileNames(1)))
					{
						if (!sourceControl.IsItemCheckedOut(item.ProjectItem.get_FileNames(1)))
						{
							checkOutResult = sourceControl.CheckOutItem(_entityItem.get_FileNames(1));
							foreach (ProjectItem scriptItem in item.ProjectItem.ProjectItems)
							{
								if (!sourceControl.IsItemCheckedOut(scriptItem.get_FileNames(1)))
								{
									checkOutResult = checkOutResult & sourceControl.CheckOutItem(scriptItem.get_FileNames(1));
								}
							}
						}
					}
					if (checkOutResult)
					{
						MetadataService service = GetMetaService();
						RetrieveEntityRequest request = new RetrieveEntityRequest();
						request.LogicalName = entityNode.InnerText.ToLower();
						request.EntityItems = EntityItems.EntityOnly;
						request.RetrieveAsIfPublished = false;
						RetrieveEntityResponse response = service.Execute(request) as RetrieveEntityResponse;

						string editPageURL = String.Format(@"{1}/Tools/SystemCustomization/Entities/manageEntity.aspx?entityId={0}", response.EntityMetadata.MetadataId.Value, VS4CRM.Lib.Context.CRMServerURL);

						ProcessStartInfo pi = new ProcessStartInfo("iexplore.exe", editPageURL);
						System.Diagnostics.Process p = new System.Diagnostics.Process();
						p.StartInfo = pi;
						
						p.EnableRaisingEvents = true;
						//p.Exited += new EventHandler(_host.p_Exited);
						p.Start();
						//_host.EventErgs.Add(p.Id, _entityItem);
						//DTEInstance.Application.Windows.Item(Constants.vsWindowKindWebBrowser).Activate();
						//DTEInstance.Application.ExecuteCommand("View.URL", editPageURL);
					}
					else
					{
						MessageBox.Show("Can Not CheckOut Entity");
					}

				}

			}

		}

		
		private MetadataService GetMetaService()
		{
			MetadataService service = new MetadataService();
			CrmAuthenticationToken token = new CrmAuthenticationToken();
			token.OrganizationName = VS4CRM.Lib.Context.OrgName;
			service.CrmAuthenticationTokenValue = token;

			service.Credentials = System.Net.CredentialCache.DefaultCredentials;

			service.PreAuthenticate = true;

			return service;
		}

		#endregion

	}
}
